import { Injectable, Inject, Scope } from '@nestjs/common';
import { CreateOperlogDto } from './dto/create-operlog.dto';
import { UpdateOperlogDto } from './dto/update-operlog.dto';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { ResultData } from 'src/common/utils/result';
import { AxiosService } from 'src/module/common/axios/axios.service';
import { PrismaService } from '@/module/common/prisma/prisma.service';

@Injectable({ scope: Scope.REQUEST })
export class OperlogService {
    constructor(
        @Inject(REQUEST)
        private readonly request: Request & { user: any },
        private readonly axiosService: AxiosService,
        private readonly prisma: PrismaService
    ) { }
    create(createOperlogDto: CreateOperlogDto) {
        return 'This action adds a new operlog';
    }

    async findAll(query: any) {
        const { pageSize, pageNum, orderByColumn, isAsc } = query;

        // 分页参数
        const skip = pageSize && pageNum ? pageSize * (pageNum - 1) : undefined;
        const take = pageSize ? +pageSize : undefined;

        // 排序参数
        const orderBy = orderByColumn && isAsc ? {
            [orderByColumn]: isAsc === 'ascending' ? 'asc' : 'desc', // 根据 isAsc 的值映射排序方向
        } : undefined;
        // 查询数据
        const [list, total] = await Promise.all([
            this.prisma.operLog.findMany({
                skip,
                take,
                orderBy,
            }),
            this.prisma.operLog.count()
        ])
        return ResultData.ok({
            list,
            total,
        });
    }

    async removeAll() {
        await this.prisma.operLog.deleteMany({
            where: {
                operId: {
                    not: undefined
                },
            }
        });
        return ResultData.ok();
    }

    findOne(id: number) {
        return `This action returns a #${id} operlog`;
    }

    update(id: number, updateOperlogDto: UpdateOperlogDto) {
        return `This action updates a #${id} operlog`;
    }

    remove(id: number) {
        return `This action removes a #${id} operlog`;
    }

    /**
     * @description: 录入日志
     */
    async logAction({
        resultData,
        costTime,
        title,
        handlerName,
        errorMsg,
        businessType,
    }: {
        resultData?: any;
        costTime: number;
        title: string;
        handlerName: string;
        errorMsg?: string;
        businessType: number;
    }) {
        const { originalUrl, method, ip, body, query } = this.request;
        const { user } = this.request.user;
        const operLocation = await this.axiosService.getIpAddress(ip);

        const params = {
            title,
            method: handlerName,
            operName: user.nickName,
            deptName: user.deptName,
            operUrl: originalUrl,
            requestMethod: method.toUpperCase(),
            operIp: ip,
            costTime: costTime,
            operLocation: operLocation,
            operParam: JSON.stringify({ ...body, ...query }),
            jsonResult: JSON.stringify(resultData),
            errorMsg,
            businessType,
            operatorType: 1,
            operTime: new Date(),
            status: errorMsg ? '1' : '0',
        };

        await this.prisma.operLog.create({
            data: params
        })
    }
}
